#!/usr/bin/python3

import os,sys
import re
import tkinter as tk
from tkinter import ttk
import importlib

class PlatformSelector:

    def __init__(self) -> None:
        pass

    def select(self):
        '''
        显示平台选择器的选择页面并进行选择
        '''
        print("选择平台")
        self.platforms = []
        self.readFiles(os.path.join(os.getcwd().replace("\\","/"),"platform"),self.platforms,True)
        self.createWnd()
        print(self.platforms)

    def appendTreeItem(self,list:list,tree:ttk.Treeview,node):
        '''
        添加树状视图的节点，递归调用 \n
        list:当前层次的文件结构树的列表 \n
        tree:Treeview \n
        node:当前节点要添加的父节点的ID \n
        '''
        index = 0
        # 遍历链表获取当前项
        for item in list:
            if not isinstance(item,dict):
                continue
            if "path" in item:
                path = item['path']
            else:
                path = item
            # 如果该项里,包含键值fileName则说明是一个具体的型号
            if 'fileName' in item:
                item['treeNode'] = tree.insert(node,index,item['fileName'],text=item['fileName'],values=(path))
                index = index + 1
            if 'groupName' in item :
                item['treeNode'] = tree.insert(node,index,item['groupName'],text=item['groupName'],values=(path))
                self.appendTreeItem(item["items"],tree,item['treeNode'])
    
    def configProject(self,event):
        '''
        获取到平台相关脚本后进入项目配置页面
        '''
        if not "groupName" in self.tree.item(self.tree.focus())["values"][0]:
            filename = self.tree.item(self.tree.focus())["values"][0]
            filenames = filename.split("/")
            sys.path.append(filename.replace(filenames[-1],""))
            self.platformlib = importlib.import_module(filenames[-1].replace(".py",""))
            self.window.destroy()
            self.configurer = self.platformlib.Configurer()
            self.configurer.config()
            
    def createWnd(self):
        '''
        创建主窗口
        '''
        # 创建主窗口
        self.window = tk.Tk()
        self.window.title("选择平台脚本")
        self.window.geometry("600x500+200+20")
        # 创建树状列表
        self.treeStyle = ttk.Style()
        self.treeStyle.configure("new.Treeview",font = ("汉仪粗圆简",20),rowheight=int(20*2.5))
        self.tree = ttk.Treeview(self.window,style="new.Treeview",show="tree")
        self.appendTreeItem(self.platforms,self.tree,"")
        self.tree.place(relx=0.004,rely=0.028,relwidth=0.964,relheight=0.95)
        self.scrollStyle = ttk.Style()
        self.scrollStyle.layout('arrowless.Vertical.TScrollbar',[('Vertical.Scrollbar.trough',{'children':[('Vertical.Scrollbar.thumb',{'expand':'1','sticky':'nswe'})],'sticky':'ns'})])
        self.vScroll1 = ttk.Scrollbar(self.window,orient='vertical',command=self.tree.yview,style='arrowless.Vertical.TScrollbar')
        self.vScroll1.place(relx=0.971,rely=0.028,relwidth=0.024,relheight=0.958)
        self.tree.configure(yscrollcommand=self.vScroll1.set)
        self.tree.bind('<Double-Button-1>',self.configProject)
        self.window.mainloop()

    def readFiles(self,dir:str,container:list,isErgodic:bool) -> bool:
        '''
        读取指定目录下的文件并添加到列表 \n
        dir:要搜索的目录 \n
        container:接收的容器\n
        isErgodic:是否递归
        '''
        files = os.listdir(dir)
        if not isinstance(container,list):
            # 如果传递进来的容器不是列表
            return False
        for file in files:
            # 检查文件拓展名
            if re.search('.py$',file) != None:
                container.append({"fileName":file,"path":os.path.join(dir,file)})
            if os.path.isdir(os.path.join(dir,file)):
                # 检查是否为Python的自动生成目录
                if file.startswith("__"):
                    continue
                container.append({"groupName":file,"items":[]})
                if isErgodic:
                    self.readFiles(os.path.join(dir,file),container[-1]["items"],True)
        return True

class CBuilder:

    def __init__(self) -> None:
        pass

    '''run
    :param  self:
    '''
    def run(self):
        self.platformSelector = PlatformSelector()
        self.platformSelector.select()

if __name__ == '__main__':
    cbuilder = CBuilder()
    cbuilder.run()